package counter

import (
	"gitee.com/Luna-CY/hui-hui/internal/logger"
	"github.com/shirou/gopsutil/v3/disk"
	"github.com/shirou/gopsutil/v3/net"
	"time"
)

func (cls *Counter) counter() {
	var now = time.Now()

	// 网络
	if cls.month != int(now.Month()) {
		cls.month = int(now.Month())

		cls.networkReset()
	}

	networks, err := net.IOCounters(true)
	if nil != err {
		logger.GetLogger().Sugar().Errorf("Worker.Counter 获取网络IO数据失败: %s", err)

		return
	}

	if 0 != len(cls.beforeNetworks) {
		for index, network := range networks {
			cls.networkIOCount(network.Name, network.BytesSent-cls.beforeNetworks[index].BytesSent, network.BytesRecv-cls.beforeNetworks[index].BytesRecv)
		}
	}

	cls.beforeNetworks = networks

	// 磁盘
	disks, err := disk.IOCounters()
	if nil != err {
		logger.GetLogger().Sugar().Errorf("Worker.Counter 获取磁盘IO数据失败: %s", err)

		return
	}

	if 0 != len(cls.beforeDisks) {
		var read uint64
		var write uint64

		for index, stat := range disks {
			read += stat.ReadBytes - cls.beforeDisks[index].ReadBytes
			write += stat.WriteBytes - cls.beforeDisks[index].WriteBytes
		}

		cls.diskIOCount(read, write)
	}

	cls.beforeDisks = disks
}
